<?php

declare(strict_types=1);

namespace App\Common\Service\Affiliate;

use App\Common\Libary\Third\Fanli;
use App\Common\Libary\Third\Pdd;
use App\Common\Libary\Third\TaoBao;
use App\Common\Libary\Third\Wph;
use App\Common\Service\ShortChainService;
use App\CustHub\Model\ChRobot;
use App\CustHub\Model\ChRoom;
use App\CustHub\Service\AffiliatePidService;
use App\Setting\Service\SettingConfigService;
use Carbon\Carbon;
use Hyperf\Di\Annotation\Inject;
use function Hyperf\Collection\collect;

class TransferChainService
{
    public array $tranUrls = [];

    public string $doutoken;

    public string $searchTbUrl = '';

    public string $quanUrl = '';

    public string $_domain = 'https://uhuidog.kuaizhan.com/';

    #[Inject]
    protected ShortChainService $chainService;

    #[Inject]
    protected AffiliatePidService $pidService;


    public function tranSendText(string $content, array $config, array $ext = [], array $filterContent = [], array $replaceList = [])
    {
        if ($cut = $this->checkNeedTran($content, $filterContent)) {
            $typeArr = [
                'jd','wph','pdd'
            ];
            if(!in_array($cut,$typeArr)){
                $type = 'taobao';
            }elseif ($cut == 'jx'){
                $type = 'jd';
            }else{
                $type = $cut;
            }

            if(!isset($config[$type])){
                return false;
            }

            $pidInfo = $this->pidService->getPidInfo($config[$type]['affiliate_pid_id']);
            $model = $config[$type]['mode'];
            if(empty($pidInfo) || $model == 1){
                //转播原文则不进行转链操作
                return $content;
            }
            $fanli = new Fanli();
            $tips = "";
            if ($cut == 'wph') {
                $wph = new Wph();
                $content = $wph->setPid($pidInfo->pid)
                    ->setAccessToken($pidInfo->account->access_token)
                    ->transferChain($model,$content,$this->tranUrls);
            }elseif ($cut == 'jd'){
                $content = $fanli->tranSearchJd($content, $this->tranUrls,$pidInfo->pid);
            }elseif ($cut == 'jx'){
                $content = $fanli->tranSearchJx($content, $this->tranUrls);
            }elseif ($cut == 'pdd'){
                $pdd = new Pdd();
                $customParameters = [
                    'uid' => 1,
                    'ext' => [
                    ]
                ];
                $content = $pdd
                    ->setPid($pidInfo->pid)
                    ->setAccessToken($pidInfo->account->access_token)
                    ->setExternalInfo($customParameters)
                    ->transferChain($content,$this->tranUrls);
            }else{
                $taobao = new TaoBao();
                if($cut == 'two'){
                    $res = $taobao->transferChain($this->searchTbUrl,$pidInfo->pid,$pidInfo->account->access_token,'',$this->quanUrl);
                }else{
                    $res = $taobao->transferChain($content,$pidInfo->pid,$pidInfo->account->access_token);
                }

                $tkl = $res['tkl'];
                $shortUrl = $res['url'];
                $content = $this->tranContent($model,$content, $tkl, $shortUrl, $cut, $ext,$taobao->pic_url);
                $tips = $ext['chain_transfer_tips'] ?? '';
            }

            if($tips){
                $key_arr = explode(PHP_EOL,$tips);
                $tips = $key_arr[array_rand($key_arr)];
                $count = substr_count($tips, '{随机表情}');
                for ($i = 0; $i < $count; $i++) {
                    $tips = preg_replace('/{随机表情}/', getRandomEmoji(), $tips, 1);
                }
                unset($count);
                $content = $content . "\n" . $tips;
            }

            //判断是否有超级红包
            if( preg_match ("/{淘宝活动(\d+\.?\d+)}/", $content, $m)!==false && !empty($m)){
                $content = str_replace($m[0],(new Fanli())->tranfromActivity($pidInfo->pid, '', $m[1],$pidInfo->account->access_token),$content);
            }

        }
        return $content;
    }


    private function tranContent($model,$content, $str_content, $thirdShortUrl, $cut, $ext, $picUrl = '')
    {
        $newString = getBeString("¥", "¥", $str_content);
        //适配IOS 16
        if($newString){
            $newString = " CZ3457 {$newString}";
        }
        $isplace = false;

        $chain_transfer_tpl = $ext['chain_transfer_tpl'] ?? '';
        if (!$newString) {
            if ($cut == 'two') {
                return $this->replace($model,$content, '','', $this->searchTbUrl, $this->quanUrl, $chain_transfer_tpl);
            } elseif ($cut == 'new'){ //新汉字口令 直接返回吧
                return $content;
            } else {
                $newString = $cut[0];
                return str_replace($newString, '', $content);
            }
        }
        empty($ext['pwd_left_mark']) && $ext['pwd_left_mark'] = '/';
        empty($ext['pwd_right_mark']) && $ext['pwd_right_mark'] = '/';

        $shareJump = container()->get(SettingConfigService::class)->getConfigByKey('share_jump')['value'];
        $query = [
            'word' => $newString,
            'image' => $picUrl
        ];
        $url = $shareJump.'?'.http_build_query($query);

        $shortUrl = $this->getShortUrl($url);
        if($shortUrl === false){
            $shortUrl = $thirdShortUrl;
        }

        if(isset($ext['pwd_rand']) && $ext['pwd_rand']){       //随机
            $str_content = $this->randToken() . $newString . $this->randToken();
        }else{
            $str_content =  $ext['pwd_left_mark'].$newString.$ext['pwd_right_mark'];
        }
        //口令形式
        $oldString = $cut[0];
        //双链接
        if ($cut == 'two') {
            return $this->replace($model,$content, $shortUrl,$str_content, $this->searchTbUrl, $this->quanUrl, $chain_transfer_tpl);
        }elseif ($cut =='new'){
            return $content."\n".$str_content;
        }else {
            return str_replace($oldString, $str_content, $content);
        }
    }

    /**
     * 双链接替换
     * @param string $content
     * @param string  $itemUrl
     * @param string $quanUrl
     * @param string  $diy_content 自定义模板样式
     */
    public function replace($model,string $content, $shortUrl, $taoToken, $itemUrl, $quanUrl, $diy_content = '')
    {
        $arr = explode("\n", $content);
        $replaced = false;
        //采用自定义模板
        if ($diy_content) {
            foreach ($arr as $k => $v) {
                if ( strpos($v, $itemUrl) !== false || (!empty($quanUrl) && strpos($v, $quanUrl) !== false)) {
                    $content = str_replace($v, '', $content);
                }
            }
            $content = preg_replace('/(^(\s|&nbsp;)*$)/m', '', $content);
            //随机数字
            if (str_contains($diy_content, '{随机数字}')) {

                $diy_content = str_replace('{随机数字}', (string)rand(0, 9), $diy_content);
            }
            //介绍文案
            if (str_contains($diy_content, '{商品文案}')) {
                $diy_content = str_replace('{商品文案}', $content, $diy_content);
            }
            //随机标签
            if (str_contains($diy_content, '{随机表情}')) {
                $count = substr_count($diy_content, '{随机表情}');
                for ($i = 0; $i < $count; $i++) {
                    $diy_content = preg_replace('/{随机表情}/', getRandomEmoji(), $diy_content, 1);
                }
                unset($send);
                unset($count);
            }
            //购买方式
            if (str_contains($diy_content, '{淘口令}')) {
                $diy_content = str_replace('{淘口令}', $taoToken, $diy_content);
            }
            if (str_contains($diy_content, '{购买链接}')) {
                $diy_content = str_replace('{购买链接}', $shortUrl, $diy_content);
            }
            return $diy_content;
        }
        if($model == 4){
            $text = $taoToken."\n".$shortUrl;
        }elseif($model == 3){
            $text = $shortUrl;
        }else{
            $text = $taoToken;
        }
        //默认原群样式
        foreach ($arr as $k => $v) {
            if (str_contains($v, $itemUrl)) {       //网址这一行
                if ($replaced) {
                    $v = str_replace("\n", '', $v);
                    $content = str_replace($v, '', $content);
                } else {
                    $replaced = true;
                    $v = str_replace("\n", '', $v);
                    $content = str_replace($v, $text, $content);
                }
            }
            if (!empty($quanUrl) && str_contains($v, $quanUrl)) {
                if ($replaced) {
                    $v = str_replace("\n", '', $v);
                    $content = str_replace($v, '', $content);
                } else {
                    $replaced = true;
                    $v = str_replace("\n", '', $v);
                    $content = str_replace($v, $text, $content);
                }
            }
        }
        return $content;
    }

    private function randToken()
    {
        $tokens = ['€', '(', ')', '￥', '《', '/', '✔', '$', '₤', '₳', '¢', '₵', '₲', '£', '₴', '₪', '₰', '🎵', '📲'];
        return $tokens[array_rand($tokens)];
    }

    /**
     * 检查是否需要转链接
     * @param string $content
     * @param string $no_words
     * @return bool|array|string
     */
    public function checkNeedTran(string $content, array $no_words = []): bool|array|string
    {
        //关键词不转换
        if ($this->wordNoChange($content, $no_words)) {
            return false;
        }

        //京东
        if (str_contains($content, 'jd.com') || str_contains($content, '#小程序://京喜')) {
            $this->getUrls($content);
            return 'jd';
        }
        if (str_contains($content, 'vip.com')) {
            $this->getUrls($content);
            return 'wph';
        }
        //拼多多
        if (str_contains($content, 'yangkeduo.com') ||
            str_contains($content, 'pinduoduo.com')
        ) {
            $this->getUrls($content);
            return 'pdd';
        }
        //淘宝双链接
        if (
            str_contains(strtolower($content), 'taobao.com') ||
            str_contains(strtolower($content), 'tmall.com') ||
            str_contains(strtolower($content), 'liangxinyao.com') ||
            str_contains(strtolower($content), 'tmall.hk')
        ) {
            //检查是否是双链接
            if ($this->getFromTwoUrl($content)) {
                return 'two';
            }
        }
        if (str_contains($content, 'douyin') || str_contains($content, 'jinritemai')) {
            $this->getUrls($content);
            return 'dy';
        }

        //口令还原
        $tokens = '\x{ffe5}|\€|\(|\)|\（|\）|\￥|\<|\>|\《|\/|\✔|\$|\₤|\₳|\¢|\¤|\฿|\₵|\₡|\₫|\ƒ|\₲|\₭|\£|\₥|\₦|\₱|\〒|\₮|\₩|\₴|\！|\，|\₪|\៛|\﷼|\₢|\ℳ|\₰|\₯|\₠|\₣|\₧|[\x{4e00}-\x{9fa5}]|[\x{1F600}-\x{1F64F}]|[\x{1F300}-\x{1F5FF}]|[\x{1F680}-\x{1F6FF}]|[\x{2600}-\x{26FF}]|[\x{2700}-\x{27BF}]';
        $preg = "#({$tokens})([a-zA-Z0-9 ]{11,30})({$tokens})#isu";
        $token = '';
        $m = [];
        if (preg_match($preg, $content, $m) !== false && !empty($m)) {
            isset($m[1]) && $m[1] && $token = $m[1];
            isset($m[3]) && $m[3] && $token .= "," . $m[3];
            return $m;
        }

        //最新口令
        if (strlen($content) > 24 && str_contains(strtolower($content), 'tk=')) {
            return 'new';
        }

        //抖音
        $preg = "#([^a-zA-Z0-9]{1,2})([A-Za-z0-9]{11,14})([^a-zA-Z0-9]{1,2})#isu";
        $m = [];
        if (preg_match($preg, $content, $m) !== false && !empty($m)) {
            $this->doutoken = $m[2];
            return 'dy';
        }
        return false;
    }

    /**
     * 关键词不转
     * @param string $content
     * @param array $black_words
     * @return bool
     */
    public function wordNoChange(string $content, array $black_words): bool
    {
        if ($black_words) {
            foreach ($black_words as $k => $v) {
                if (str_contains($content, $v)) {
                    return true;
                }
            }
        }
        return false;
    }

    private function getUrls($content): void
    {
        $array2 = [];
        $pattern = '/https?:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,}(?::\d+)?(\/[a-zA-Z0-9\-._~:\/?#@!$&\'()*+,;=]*)?/';
        preg_match_all("{$pattern}", $content, $array2);

        $urls = $array2[0];
        $this->tranUrls = $urls;
    }

    public function getFromTwoUrl($content): bool
    {
        $array2 = [];
        preg_match_all('@(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))@', $content, $array2);
        $urls = $array2[0];
        if (!str_contains($urls[0], 'id=')
            && !str_contains($urls[1], 'id=')) {
            return false;
        }
        if (str_contains($urls[0], 'quan')) {
            $this->searchTbUrl = preg_replace('/\s/u', '', $urls[1]);
            $this->quanUrl = preg_replace('/\s/u', '', $urls[0]);         //trim($urls[0]);
        } else {
            $this->searchTbUrl = preg_replace('/\s/u', '', $urls[0]);
            if(isset($urls[1])){
                $this->quanUrl = preg_replace('/\s/u', '', $urls[1]);         //trim($urls[1]);
            }
        }
        return true;
    }


    /**
     * 替换标签
     * @param string $content
     * @param array $item
     * @return array|mixed|string|string[]|null
     */
    public function replaceLabel(string $content, array $item = []): mixed
    {
        //替换淘宝商品链接
        if (str_contains($content, "{购买链接}") && in_array($item['shop_type'], [0, 1])) {
            $url = "{$this->_domain}?word={$item['taotoken']}&image={$item['pic_url']}";
            $tempUrl = $this->getShortUrl($url);
            $item['click_url'] = $tempUrl ? $tempUrl : $url;
        }

        $itemTipKey = ['{标题}', '{商品文案}', '{券价格}', '{原价}', '{券后价}', '{购买链接}', '{口令}', '{淘口令}'];        //商品标签
        $itemTipValue = [
            "{$item['title']}",
            "{$item['intro']}",
            "{$item['quan_price']}",
            "{$item['price']}",
            "{$item['after_price']}",
            "{$item['click_url']}",
            "{$item['taotoken']}",
            "{$item['taotoken']}"
        ];

        $str = '';
        if ($item) {
            foreach ($itemTipKey as $k => $v) {
                if (str_contains($content, $v)) {
                    $_s = $itemTipValue[$k];
                    $content = str_replace($v, $_s, $content);
                }
            }
        }
        $count = substr_count($content, '{随机表情}');
        for ($i = 0; $i < $count; $i++) {
            preg_match('/{随机表情}/', $str, $matches);
            $content = preg_replace('/{随机表情}/', (getRandomEmoji()), $content, 1);
        }
        return $content;
    }

    /**
     * 获取短链接
     * @param string $targetUrl
     * @return false|mixed
     */
    private function getShortUrl(string $targetUrl): mixed
    {
        try {
            $validTime = Carbon::now()->addMonth()->toDateTimeString();
            $result = $this->chainService->createChains($targetUrl,$validTime,1);
            return $result['render_url'];
        } catch (\Throwable $e) {
            logger()->debug("生成短链失败" . $e->getMessage());
            return false;
        }
    }
}